<template>
  <div class="app-container">
    <div class="search_container_warp">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        class="search_container"
      >
        <el-form-item label="比赛组别" prop="matchGroup">
          <el-select
            style="width: 120px"
            clearable
            v-model="queryParams.matchGroup"
            @change="handleQuery"
          >
            <el-option
              v-for="item in groupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="name" label="试卷名称">
          <el-input
            v-model="queryParams.name"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openDialog()"> 新增试卷</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        class="customTableClass"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
      >
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column label="试卷名称" sortable prop="name" min-width="200">
          <template #default="scope">
            <span class="clickLinkClass" @click="gotoPage(scope.row)">
              {{ scope.row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="组别"
          prop="matchGroupName"
          align="center"
          width="90"
        />
        <el-table-column label="状态" prop="status" align="center" width="80" />
        <el-table-column
          label="分数"
          prop="totalScore"
          align="center"
          width="80"
        />
        <el-table-column
          label="题数"
          prop="questionNumber"
          align="center"
          width="80"
        />
        <el-table-column
          label="单选题"
          prop="singleNumber"
          align="center"
          width="80"
        />
        <el-table-column
          label="多选题"
          prop="multipleNumber"
          align="center"
          width="80"
        />
        <el-table-column
          label="判断题"
          prop="judgmentNumber"
          align="center"
          width="80"
        />

        <!--        
				<el-table-column
					label="备注"
					prop="remark"
					align="center"
					min-width="120"
				/> 
				-->
        <el-table-column label="操作" prop="code" align="center" width="70">
          <template #default="scope">
            <el-icon :size="16" class="editIconClass">
              <Edit @click="editFn(scope.row)" />
            </el-icon>
            <el-icon
              :size="16"
              class="deleteIconClass"
              v-if="scope.row.status !== '已审核'"
            >
              <i-ep-delete @click="handleDelete(scope.row.id)" />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 竞赛试题弹窗  -->
    <el-dialog
      v-if="dialog.visible"
      modal-class="maxHeightClass"
      v-model="dialog.visible"
      title="竞赛试题"
      width="600px"
      draggable
      align-center
      @close="closeExamDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="formData.name" :disabled="examDataDiabled" />
        </el-form-item>
        <el-form-item label="比赛组别" prop="matchGroup">
          <el-select v-model="formData.matchGroup" :disabled="examDataDiabled">
            <el-option
              v-for="item in groupOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单选分值" prop="score1">
          <el-input
            :disabled="examDataDiabled"
            v-model="formData.score1"
            @change="(data) => changeFn(data, 'score1')"
          />
        </el-form-item>
        <el-form-item label="多选分值" prop="score2">
          <el-input
            :disabled="examDataDiabled"
            v-model="formData.score2"
            @change="(data) => changeFn(data, 'score2')"
          />
        </el-form-item>
        <el-form-item label="判断分值" prop="score3">
          <el-input
            :disabled="examDataDiabled"
            v-model="formData.score3"
            @change="(data) => changeFn(data, 'score3')"
          />
        </el-form-item>
        <el-form-item label="状态" prop="statusCode">
          <el-radio-group v-model="formData.statusCode">
            <el-radio :value="0">未审核</el-radio>
            <el-radio :value="1">已审核</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            :disabled="examDataDiabled"
            v-model="formData.remark"
            type="textarea"
            placeholder=""
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeExamDialog">取 消</el-button>
          <el-button type="primary" @click="handleExamSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getDictionaryPage } from "@/api/examManagement";
import {
  getTestPaperList,
  paperCreate,
  paperUpdate,
  paperDelete,
} from "@/api/examPaperManagement";
import { ItemPageVO, Options, ItemForm } from "@/api/examPaperManagement/types";
import { queryFilter, computeHeiht, isNumber } from "@/utils/index";

defineOptions({
  name: "ExamPaperManagement",
  inheritAttrs: false,
});

const router = useRouter();
const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);
const groupOptions = ref<Options[]>([]);

const loading = ref(false);
const dataList = ref<ItemPageVO[]>([]);
const originaldataList = ref<ItemPageVO[]>([]);

const dialog = reactive<any>({
  title: "",
  visible: false,
});

const queryParams = reactive<any>({
  matchGroup: null,
});

const rules = reactive({
  name: [
    {
      required: true,
      message: " ",
      trigger: "change",
    },
  ],
  matchGroup: [{ required: true, message: " ", trigger: "change" }],
  score1: [{ required: true, message: " ", trigger: "change" }],
  score2: [{ required: true, message: " ", trigger: "change" }],
  score3: [{ required: true, message: " ", trigger: "change" }],
});

const formData = reactive<ItemForm>({});
const examDataDiabled = computed(() => formData.status === "已审核");

/** 查询 */
function handleQuery() {
  let { matchGroup, name } = queryParams;
  let arr: Options[] = [
    { label: "matchGroup", value: matchGroup },
    { label: "name", value: name },
  ];
  if (matchGroup || name) {
    dataList.value = queryFilter(originaldataList.value, arr);
  } else {
    query();
  }
}

/** 接口查询 */
function query() {
  loading.value = true;
  getTestPaperList(queryParams)
    .then(({ data }) => {
      data.forEach((item: any) => {
        item.statusCode = item.status === "已审核" ? 1 : 0;
        item.matchGroupName = item.matchGroup;
        item.matchGroup = groupOptions.value.find(
          (v) => v.label === item.matchGroup
        )?.value;
      });

      dataList.value = data;
      originaldataList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  query();
}

function gotoPage(data: any) {
  router.push({
    path: `/systemManagement/questionManagement`,
    query: data,
  });
}

function changeFn(data: any, name: any) {
  let num: number | undefined | string = data - 0;
  if (num <= 0 || !isNumber(num)) {
    num = undefined;
  } else if (String(num).indexOf(".") >= 0) {
    num = Number(num).toFixed(1);
  }

  if (name === "score1") {
    formData.score1 = num;
  } else if (name === "score2") {
    formData.score2 = num;
  } else {
    formData.score3 = num;
  }
}

function openDialog() {
  dialog.title = "新增试卷";
  dialog.visible = true;
  Object.assign(formData, {
    id: "",
    matchGroup: "",
    name: "",
    score1: "",
    score2: "",
    score3: "",
    statusCode: 0,
    status: "",
    remark: "",
  });
}

function editFn(data: ItemPageVO) {
  Object.assign(formData, data);
  dialog.title = "编辑试卷";
  dialog.visible = true;
}

function closeExamDialog() {
  dialog.visible = false;
}
function handleExamSubmit() {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      let params: any = {
        id: "",
        matchGroup: formData.matchGroup,
        name: formData.name,
        remark: formData.remark,
        score1: formData.score1,
        score2: formData.score2,
        score3: formData.score3,
        status: formData.statusCode,
      };
      if (formData.id) {
        params.id = formData.id;
        paperUpdate(params).then((res) => {
          ElMessage.success("修改成功");
          closeExamDialog();
          query();
        });
      } else {
        paperCreate(params).then((res) => {
          ElMessage.success("新增成功");
          closeExamDialog();
          query();
        });
      }
    }
  });
}
/** 删除 */
function handleDelete(id?: number) {
  ElMessageBox.confirm("确认删除数据项?", "确认删除", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "error",
  }).then(() => {
    loading.value = true;
    paperDelete(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

onMounted(async () => {
  let { data } = await getDictionaryPage("MATCH_GROUP", 1);
  groupOptions.value = data.map((v: any) => {
    return {
      label: v.name,
      value: v.myKey,
    };
  });
  query();
  computeHeiht();
});
</script>
<style lang="scss" scoped></style>
